﻿using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Web.UI;
using System.Web;
using System.Web.UI.WebControls;


namespace XunPan.Web.Globals
{


	public class FileUtility
	{

		/// <summary> 
		/// 由原始文件名生成以时间戳和随机数组合的文件名
		/// 返回新的唯一文件名包括扩展名
		/// </summary> 
		/// <param name="seed">种子数</param> 
		public static string CreateUniqueNumberBySeed(int seed)
		{

			string number = DateTime.Now.ToFileTimeUtc().ToString() + (new Random(seed)).Next().ToString();

			return number;
		}


		/// <summary> 
		/// 由原始文件名生成以时间戳和随机数组合的文件名
		/// 返回新的唯一文件名包括扩展名
		/// </summary> 
		/// <param name="originalFileName">原始文件名(包括扩展名)</param> 
		public static string CreateUniqueFileName(string originalFileName)
		{

			string fileExtension = System.IO.Path.GetExtension(originalFileName).ToLower();

			string filename = DateTime.Now.ToFileTimeUtc().ToString() + ((new Random()).Next() / 1000).ToString() + fileExtension;

			return filename;
		}



		/// <summary> 
		/// 上传文件的方法,成功时返回上传文件的完整名称，否则返回Null 
		/// 上传图片类型文件，对“.gif,.png,.bmp,.jpg”敏感 
		/// </summary> 
		/// <param name="FU">FileUpload控件</param> 
		/// <param name="path">上传文件的绝对路径</param> 
		/// <param name="filename">上传文件的保存文件名，不包含扩展名</param> 
		/// <returns>成功时返回上传文件的完整名称，否则返回Null</returns> 
		public static string UploadImage(FileUpload FU, string path, string filename)
		{
			if (filename == null) {
				filename = System.IO.Path.GetFileNameWithoutExtension(FU.FileName);
			}
			string fileExtension = System.IO.Path.GetExtension(FU.FileName).ToLower();
			string[] allowedExtensions = {
				".gif",
				".png",
				".bmp",
				".jpg"
			};
			for (int i = 0; i <= allowedExtensions.Length - 1; i++) {
				if (fileExtension == allowedExtensions[i]) {
					string url = path + filename + fileExtension;
					FU.SaveAs(url);
					return filename + fileExtension;
				}
			}
			return null;
		}

		/// <summary> 
		/// 上传文件的方法,成功时返回上传文件的完整名称，否则返回Null 
		/// 上传一个Doc文档，对扩展名“.doc”敏感 
		/// </summary> 
		/// <param name="FU"></param> 
		/// <param name="path"></param> 
		/// <param name="filename"></param> 
		/// <returns></returns> 
		public static string UploadDoc(FileUpload FU, string path, string filename)
		{
			string fileExtension = System.IO.Path.GetExtension(FU.FileName).ToLower();
			string[] allowedExtensions = { ".doc" };
			for (int i = 0; i <= allowedExtensions.Length - 1; i++) {
				if (fileExtension == allowedExtensions[i]) {
					string url = path + filename + fileExtension;
					FU.SaveAs(url);
					string r = WordToHtmlFile(url);
					if (r == "true") {
						return filename + fileExtension;
					} else {
						return r;
					}
				}
			}

			return null;
		}

		/// <summary> 
		/// 上传文件的方法,成功时返回上传文件的完整名称，否则返回Null 
		/// 上传任意文件 
		/// </summary> 
		/// <param name="FU"></param> 
		/// <param name="path"></param> 
		/// <param name="filename"></param> 
		/// <returns></returns> 
		public static string UploadFile(FileUpload FU, string path, string filename)
		{
			string fileExtension = System.IO.Path.GetExtension(FU.FileName).ToLower();
			string url = path + filename + fileExtension;
			FU.SaveAs(url);
			return filename + fileExtension;

		}

		/// <summary> 
		/// 从网站本地下载文件 
		/// </summary> 
		/// <param name="p">下载文件所在页面对象</param> 
		/// <param name="fileurl">下载文件的虚拟路径</param> 
		public static void DownloadFile(Page p, string fileUrl)
		{
			if (fileUrl == null || fileUrl.Length < 1) {
				return;
			}

			//Check the file type 
			string fileExtension = System.IO.Path.GetExtension(fileUrl);
			if (fileExtension != null && fileExtension.Length > 0) {
				fileExtension = fileExtension.ToLower() + ",";
				string disabledTypes = ".asa,.asax,.asp,.aspx,.cs,.config,.jsp,.master,.mdb,";
				if (disabledTypes.IndexOf(fileExtension) >= 0) {
					return;
				}
			}

			string fname = p.Server.MapPath(fileUrl);
			FileInfo finf = new FileInfo(fname);
			if (!finf.Exists) {
				return;
			}
			p.Response.Charset = "UTF-8";
			p.Response.AddHeader("Content-Disposition", "attachment;filename=" + finf.Name);
			p.Response.AddHeader("Content-Length", finf.Length.ToString());
			p.Response.ContentType = "application/octet-stream";

			try {
				//Clear the buffer 
				p.Response.Clear();
				p.Response.Buffer = true;

				p.Response.WriteFile(fname);
				p.Response.Flush();
				p.Response.End();
			} catch (Exception generatedExceptionName) {
				return;
			}

		}

		/// <summary> 
		/// 清除上传过程中生成的多余图片 
		/// </summary> 
		/// <param name="FilePath">文件在服务器上的路径</param> 
		public static void ClearRedundancyImages(System.Web.UI.Page filepath)
		{
			//'定义文件名和文件路径 

			//'定义保留文件的列表 
			//Dim filelist As New List(Of String)()


			//' ~/productDesign/IMGS文件夹和~/productTechnics/IMGS文件夹 
			//'现在只读取了产品模块相关的表，增加标准模块时只需要更改相关存储过程读出相关表，并在文件夹列表中添加相应的文件夹 

			//'Dim productfilepath As String() = {"~/productDesign/IMGS/ClassPicture/", "~/productDesign/IMGS/ProductPicture/", "~/productDesign/IMGS/Knowledge/", "~/productDesign/IMGS/Mould4P/", "~/productDesign/IMGS/Resource4P/", "~/ProductTechnics/IMGS/CATIA4/", _
			//'"~/ProductTechnics/IMGS/UG4/", "~/ProductTechnics/IMGS/Knowledge/"}
			//'Dim SQLC As New SqlConnection(ConfigurationManager.ConnectionStrings("ModelNet2.0ConnectionString").ConnectionString)
			//'Dim SQLM As New SqlCommand("select_product_imgs", SQLC)
			//'SQLM.CommandType = CommandType.StoredProcedure
			//'SQLC.Open()
			//'Dim Sdr As SqlDataReader = SQLM.ExecuteReader()
			//'While Sdr.Read()
			//'    filelist.Add(page.Server.MapPath(Sdr(0).ToString()))
			//'End While
			//'For i As Integer = 0 To productfilepath.Length - 1
			//'    Dim PathInfo As New DirectoryInfo(page.Server.MapPath(productfilepath(i)))
			//'    Dim tempFiles As FileSystemInfo() = PathInfo.GetFileSystemInfos()
			//'    DeleteCommonFiles(filelist, tempFiles)
			//Next

		}

		/// <summary> 
		/// 清除上传过程中产生的多余word文档及生成的html文件 
		/// </summary> 
		/// <param name="page">文件在服务器上的路径</param> 
		public static void ClearRedundancyDocs(System.Web.UI.Page page)
		{
			//Dim filelist As New List(Of String)()
			//Dim filepath As String() = {"~/productDesign/Docs/", "~/ProductTechnics/Docs/"}
			//Dim SQLC As New SqlConnection(ConfigurationManager.ConnectionStrings("ModelNet2.0ConnectionString").ConnectionString)
			//Dim SQLM As New SqlCommand("select_product_docs", SQLC)
			//SQLM.CommandType = CommandType.StoredProcedure
			//SQLC.Open()
			//Dim Sdr As SqlDataReader = SQLM.ExecuteReader()
			//While Sdr.Read()
			//    filelist.Add(page.Server.MapPath(Sdr(0).ToString()))
			//End While
			//For i As Integer = 0 To filepath.Length - 1
			//    Dim PathInfo As New DirectoryInfo(page.Server.MapPath(filepath(i)))
			//    DeleteDocFiles(filelist, PathInfo, Nothing)
			//Next

		}

		/// <summary> 
		/// 注意！需要很高的权限才能删除由doc生成的html文件和files文件夹！ 
		/// </summary> 
		/// <param name="page">控件所在页面对象</param> 
		/// <param name="filename">待删除的文件名称（含路径）</param> 
		/// <param name="isDocHtml">是否需要删除文件名相同，但是扩展名不同的文件</param> 
		public static void DeleteFile(System.Web.UI.Page page, string filename, bool isDocHtml)
		{
			string path = System.IO.Path.GetDirectoryName(filename);
			string fn = System.IO.Path.GetFileName(filename);
			if (path != null && path.Length > 0 && fn != null && fn.Length > 0) {
				DirectoryInfo PathInfo = new DirectoryInfo(page.Server.MapPath(path));
				List<string> reserved = new List<string>();
				if (isDocHtml) {
					DeleteDocFiles(reserved, PathInfo, fn);
				} else {
					DeleteCommonFiles(reserved, PathInfo.GetFileSystemInfos(fn));
				}
			}
		}

		/// <summary> 
		/// 批量删除一般文件
		/// </summary> 
		/// <param name="reserveFileList">文件名列表</param> 
		/// <param name="allFiles">文件集合</param> 
		private static void DeleteCommonFiles(List<string> reserveFileList, FileSystemInfo[] allFiles)
		{
			int fileNum = allFiles.Length;
			string item = null;


			for (int i = 0; i <= fileNum - 1; i++) {
				item = allFiles[i].FullName.ToLower();
				if (!reserveFileList.Contains(item)) {
					try {
						allFiles[i].Delete();
					} catch (Exception generatedExceptionName) {
					}
				}
			}
		}

		/// <summary> 
		/// 批量删除文件
		/// </summary> 
		/// <param name="reserveFileList">文件名列表</param> 
		/// <param name="PathInfo">文件目录</param> 
		/// <param name="deletedFile">已删除的文件</param> 
		private static void DeleteDocFiles(List<string> reserveFileList, DirectoryInfo PathInfo, string deletedFile)
		{
			FileSystemInfo[] allFiles = null;
			if (deletedFile != null && deletedFile.Length > 0) {
				string fn = System.IO.Path.GetFileNameWithoutExtension(deletedFile);
				if (fn != null && fn.Length > 0) {
					allFiles = PathInfo.GetFileSystemInfos(fn + ".*");
				}
			}
			if (allFiles == null) {
				allFiles = PathInfo.GetFileSystemInfos();
			}
			int fileNum = allFiles.Length;
			for (int i = 0; i <= fileNum - 1; i++) {
				string fullName = allFiles[i].FullName;
				string ext = allFiles[i].Extension;
				if (ext == ".html") {
					fullName = allFiles[i].FullName.Substring(0, allFiles[i].FullName.Length - 4) + "doc";
				} else if (ext == ".files") {
					fullName = allFiles[i].FullName.Substring(0, allFiles[i].FullName.Length - 5) + "doc";
				}

				string item = fullName.ToLower();

				if (!reserveFileList.Contains(item)) {
					if (allFiles[i].Attributes == FileAttributes.Directory) {
						FileSystemInfo[] tempfiles = new DirectoryInfo(allFiles[i].FullName).GetFileSystemInfos();
						for (int j = 0; j <= tempfiles.Length - 1; j++) {
							try {
								tempfiles[j].Delete();
							} catch (Exception generatedExceptionName) {
							}
						}
					}
					try {
						allFiles[i].Delete();
					} catch (Exception generatedExceptionName) {
					}
				}
			}

		}


		/// <summary> 
		/// 转换word文件为html，暂时预留功能
		/// </summary> 
		/// <param name="WordFilePath">word文件的全路径</param> 

		public static string WordToHtmlFile(string WordFilePath)
		{
			//'String test = ""; 
			//Dim newApp As Microsoft.Office.Interop.Word.Application
			//' new Microsoft.Office.Interop.Word.Application(); 
			//Dim doc As Microsoft.Office.Interop.Word.Document
			//Dim Target As Object
			//Dim Unknown As Object

			//Try

			//    newApp = New Microsoft.Office.Interop.Word.Application()
			//Catch e As Exception
			//    ' "error1"; 
			//    ' System.Windows.Forms.MessageBox.Show(e.Message); 
			//    Return e.Message
			//End Try

			//Try
			//    ' 指定原文件和目标文件 
			//    Dim Source As Object = WordFilePath
			//    Dim SaveHtmlPath As String = WordFilePath.Substring(0, WordFilePath.Length - 3) & "html"
			//    Target = SaveHtmlPath

			//    ' 缺省参数 
			//    Unknown = Type.Missing

			//    '为了保险,只读方式打开 
			//    Dim [readOnly] As Object = True

			//    ' 打开doc文件 
			//    doc = newApp.Documents.Open(Source, Unknown, [readOnly], Unknown, Unknown, Unknown, _
			//    Unknown, Unknown, Unknown, Unknown, Unknown, Unknown, _
			//    Unknown, Unknown, Unknown, Unknown)
			//Catch e As Exception

			//    '"error2"; 
			//    ' System.Windows.Forms.MessageBox.Show(e.Message); 
			//    Return e.Message
			//End Try

			//Try
			//    ' 指定另存为格式(rtf) 
			//    Dim format As Object = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML
			//    ' 转换格式 
			//    doc.SaveAs(Target, format, Unknown, Unknown, Unknown, Unknown, _
			//    Unknown, Unknown, Unknown, Unknown, Unknown, Unknown, _
			//    Unknown, Unknown, Unknown, Unknown)
			//Catch e As Exception
			//    '"error3"; 
			//    ' System.Windows.Forms.MessageBox.Show(e.Message); 
			//    Return e.Message
			//Finally
			//    ' 关闭文档和Word程序 
			//    doc.Close(Unknown, Unknown, Unknown)
			//    newApp.Quit(Unknown, Unknown, Unknown)
			//End Try
			return "true";
		}


		public static bool ResponseFile(string filename, Int32 filesize, string contenttype, byte[] filedata)
		{
			HttpContext context = HttpContext.Current;

			context.Server.ScriptTimeout = 600;
			context.Response.Buffer = true;
			context.Response.Clear();
			context.Response.ContentType = contenttype;
			context.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + filename + "\";");
			context.Response.AddHeader("Content-Length", filesize.ToString());
			// buffer of the file data

			context.Response.BinaryWrite(filedata);

			// End the response
			context.Response.End();

            return true;
		}


	}
}
